package com.cet.algorithm.数组;

/**
 * @program: algorithm
 * @description: 移除元素
 * @author: 陈恩涛
 * @create: 2022-03-08 21:26
 **/
public class LC27 {
    public static int removeElement(int[] nums, int val) {
        int length = nums.length;
        for(int i = 0; i < length; i++){
            while(nums[i] == val && i < length){
                System.arraycopy(nums,i + 1,nums,i,nums.length - i - 1);
                length--;
            }
        }
        return length;
    }

    /**
     * 快慢指针实现
     * 快指针寻找新数组的值
     * 慢指针为新数组的下标
     * @param nums
     * @param val
     * @return
     */
    public static int removeElementBT(int[] nums, int val) {

        // 快慢指针
        int fastIndex = 0;
        int slowIndex;
        for (slowIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;

    }

    public static void main(String[] args) {
        int[] a = {3, 2, 3, 2, 1};
        System.out.println(removeElementBT(a, 3));
        for (int i : a) {
            System.out.println(i);
        }
    }


}
